package com.ht.api.call.func.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.sql.DataSource;

import com.ht.api.bean.AjaxResult;
import com.ht.api.bean.LoginBean;
import com.ht.api.call.func.IFunctionCall;
import com.ht.api.db.Db;
import com.ht.api.db.DbConfig;
import com.ht.api.db.DbList;
import com.ht.api.db.Entity;
import com.ht.api.db.exception.HtException;
import com.ht.api.util.UserUtil;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 查询tag_relation数据
 * @author asq
 * @createTime 2025年2月27日 15:25:57
 */
@Slf4j
public class QueryTagRelationFunctionCall implements IFunctionCall {

	@Override
	public String getName() {
		return "查询tag_relation";
	}

	@Override
	public JSONObject execute(LoginBean me, JSONObject param, AjaxResult result) {
		// 获取参数
		String relationId = param.getStr("relation_id");
		String naturalId = param.getStr("natural_id");
		String tagCode = param.getStr("tag_code");
		Integer status = param.getInt("status");
		List<String> groupIds = param.getBeanList("group_id", String.class);
		if (StrUtil.isBlank(relationId) && StrUtil.isBlank(naturalId)) {
			throw new HtException("relation_id和natural_id参数至少要传一个~");
		}

		// 组装sql
		String sql = """
				SELECT
				    t.main_id,
				    t.tag_name,
				    t.tag_type,
				    t.tag_code,
				    t.rules,
				    t.remark,
				    t.`status`,
				    t.tag_color,
				    t.tag_icon,
				    tg.tag_group_name,
				    g.group_name,
				    g.main_id group_id,
				    tg.main_id tag_group_id 
				  FROM tag_relation tr
				    inner join tag t on t.main_id=tr.tag_id
				    inner JOIN tag_group tg ON tg.main_id=t.tag_group_id
				    inner join `group` g on g.main_id=tg.group_id
				  WHERE %s and tr.sys_deleted=1 and tr.status=1
				  ORDER BY g.sys_time ASC, tg.sys_time ASC, t.sys_time ASC
				""";
		List<String> params = new ArrayList<>();
		
		StringBuilder condition = new StringBuilder();
		if (StrUtil.isNotBlank(relationId)) {
			condition.append("tr.relation_id=?");
			params.add(relationId);
		}
		if (StrUtil.isNotBlank(naturalId)) {
			if (!condition.isEmpty()) {
				condition.append(" or ");
			}
			condition.append("tr.natural_id=?");
			params.add(naturalId);
		}
		
		StringBuilder sb = new StringBuilder("(" + condition.toString() + ")");
		if (groupIds != null && !groupIds.isEmpty()) {
			// 生成sql参数
			StringBuilder args = new StringBuilder();
			for (int i = 0; i < groupIds.size(); i++) {
				args.append("?,");
			}
			args.deleteCharAt(args.length() - 1);
			sb.append(" and g.main_id in(" + args + ")");
			params.addAll(groupIds);
		}
		if (StrUtil.isNotBlank(tagCode)) {
			sb.append(" and tr.tag_code=?");
			params.add(tagCode);
		}
		if (status != null) {
			sb.append(" and t.status=?");
			params.add(status + "");
		}
		
		sql = String.format(sql, sb.toString());
		
		// 获取租户数据源进行查询
		long tenantId = UserUtil.getLoginUser().getTenantId();
		DataSource ds = DbConfig.useTenantDb(tenantId);
		DbList list = Db.query(ds, sql, params);
		
		// 组装
		JSONArray groupTags = groupTags(list);
		return JSONUtil.createObj().set("list", groupTags);
		
	}
	
	private JSONArray groupTags(DbList tagList) {
	    // 2处理非空的数据
	    Map<String, Map<String, List<Entity>>> groupedTags = tagList.stream()
	            .filter(tag -> tag.getStr("tag_group_id") != null)  // 只处理非空的
	            .collect(Collectors.groupingBy(
	                    tag -> tag.getStr("group_id") + "," + tag.getStr("group_name"),
	                    Collectors.groupingBy(tag -> tag.getStr("tag_group_id") + "," + tag.getStr("tag_group_name"))
	            ));

	    JSONArray result = new JSONArray();

	    // 3. 处理分组数据
	    groupedTags.forEach((groupIdAndName, tagGroupMap) -> {
	        String[] groupArr = groupIdAndName.split(",");
	        JSONObject groupObject = new JSONObject();
	        groupObject.set("group_id", groupArr[0]);
	        groupObject.set("group_name", groupArr[1]);

	        JSONArray tagGroupsArray = new JSONArray();

	        tagGroupMap.forEach((tagGroupIdAndName, tags) -> {
	            // 去掉tags里面main_id为空的数据
	            List<Entity> validTags = tags.stream()
	                    .filter(tag -> tag.getStr("main_id") != null)
	                    .collect(Collectors.toList());

	            String[] tagGroupArr = tagGroupIdAndName.split(",");
	            JSONObject tagGroupObject = new JSONObject();
	            tagGroupObject.set("tag_group_id", tagGroupArr[0]);
	            tagGroupObject.set("tag_group_name", tagGroupArr[1]);
	            tagGroupObject.set("tags", validTags);
	            tagGroupsArray.put(tagGroupObject);
	        });

	        groupObject.set("tag_group", tagGroupsArray);
	        result.put(groupObject);
	    });
	    
	    // 再加上为null的没有数据的group数据
	    tagList.stream().filter(tag -> tag.getStr("tag_group_id") == null).forEach(tag -> {
	    	JSONObject groupObject = new JSONObject();
            groupObject.set("group_id", tag.getStr("group_id"));
            groupObject.set("group_name", tag.getStr("group_name"));
            groupObject.set("tag_group", new JSONArray());
            result.put(groupObject);
	    });

	    return result;
	}
}
